package com.artisan.provider.service.impl;

import com.artisan.provider.domain.TOrder;
import com.artisan.provider.mapper.TOrderMapper;
import com.artisan.provider.service.TOrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Service
public class TOrderServiceImpl implements TOrderService {

    @Autowired
    TOrderMapper tOrderMapper;

    /**
     * 从mq中的数据提取出来保存到数据库
     * @param data
     * @param channel
     * @param headers
     */

    //从那个队列拿 关联的交换机
    @RabbitListener(
            bindings = @QueueBinding(value = @Queue(value = "queue-order"),
            exchange = @Exchange(value = "exchange-order",type = "fanout"))
    )
    @RabbitHandler
    // Payload 自动取出来转map集合  @Header 动态注入数据 data是交换机 队列中的数据
    public void handleMessage(@Payload Map data,
                              Channel channel,
                              @Headers Map<String, Object> headers) {
        System.out.println("========获取到订单数据"+data+"=======;");
        try {
            //睡眠500毫秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //对接支付宝,物流系统,日志登记
        try {

            TOrder order = new TOrder();
            order.setOrderNo(data.get("orderNo").toString());
            order.setOrderStatus(0);
            order.setUserid(data.get("userid").toString());
            order.setPostage(0f);
            order.setAmout(19.8f);
            order.setRecvAddress("街道街道...");
            order.setCreateTime(new Date());
            tOrderMapper.insertSelective(order);
            Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG); //获取当前对象的id
            //第二个参数 false 是否进行批量接受
            channel.basicAck(tag,false); //消息确认
            System.out.println(data.get("orderNo")+"订单已创建");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
